package com.cskt.itripauth.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.entity.ItripUser;
import com.cskt.common.exception.ServiceException;
import com.cskt.service.ItripUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author mo
 * @Description: 自定义认证及鉴权处理器
 * @date 2020-09-22 15:13
 */
//shiro中自定义realm一般继承AuthorizingRealm，
// 然后实现getAuthenticationInfo和getAuthorizationInfo方法，来完成登录和权限的验证。
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private ItripUserService itripUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 此期没有涉及到用户的角色，所只不需要实现鉴权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 默认使用此方法进行用户正确与否验证，错误抛出异常即可
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        if (token == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_TOKEN_IS_EMPTY);
        }
        String username = JWTUtil.getUsername(token);
        //判断负载中是否存在username
        if (username == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_UNKNOWN);
        }
        //和数据库进行对比
        QueryWrapper<ItripUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_code", username);
        ItripUser user = itripUserService.getOne(queryWrapper);
        if (user == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }

        if (!JWTUtil.verify(token, username, user.getUserPassword())) {
            throw new ServiceException(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }
        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }

}
